package cs294s.liveradar;

import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import com.google.android.maps.GeoPoint;

import cs294s.liveradar.data.Blip;
import cs294s.liveradar.service.BlipManager;
import cs294s.liveradar.service.Util;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;

public class BlipCreateForm extends Activity{

	private BlipManager blipManager;

	private int myYear, myMonth, myDay, myHour, myMinute;
	static final int ID_DATEPICKER = 0;
	static final int ID_TIMEPICKER = 1;

	static final int PICK_LOCATION_REQUEST = 0;

	String currAddr;
	int currLat;
	int currLon;

	Date currDate;
	
	Geocoder geoCoder;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.blipcreate);

		blipManager = BlipManager.getInstance(this);
		geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
		currDate = new Date();
		displayTime();
		displayCurrentLocation();
		setupButtons();
	}
	
	
	private void setupButtons() {
		Button nowButton = (Button)findViewById(R.id.blipcreate_nowButton);
		Button datePickerButton = (Button)findViewById(R.id.blipcreate_datePickerButton);
		Button timePickerButton = (Button)findViewById(R.id.blipcreate_timePickerButton);

		Button hereButton = (Button)findViewById(R.id.blipcreate_hereButton);
		Button mapButton = (Button)findViewById(R.id.blipcreate_mapButton);
		Button favsButton = (Button)findViewById(R.id.blipcreate_favsButton);

		Button confirmButton = (Button)findViewById(R.id.blipcreate_confirmButton);
		Button cancelButton = (Button)findViewById(R.id.blipcreate_cancelButton);


		nowButton.setOnClickListener(nowButtonOnClickListener);
		datePickerButton.setOnClickListener(datePickerButtonOnClickListener);
		timePickerButton.setOnClickListener(timePickerButtonOnClickListener);

		hereButton.setOnClickListener(hereButtonOnClickListener);
		mapButton.setOnClickListener(mapButtonOnClickListener);
		favsButton.setOnClickListener(favsButtonOnClickListener);

		confirmButton.setOnClickListener(confirmButtonOnClickListener);
		cancelButton.setOnClickListener(cancelButtonOnClickListener);
	}

	private Button.OnClickListener nowButtonOnClickListener
	= new Button.OnClickListener(){
		@Override
		public void onClick(View v) {
			currDate = new Date();
			displayTime();
		}
	};  

	private Button.OnClickListener datePickerButtonOnClickListener
	= new Button.OnClickListener(){
		@Override
		public void onClick(View v) {
			final Calendar c = Calendar.getInstance();
			myYear = c.get(Calendar.YEAR);
			myMonth = c.get(Calendar.MONTH);
			myDay = c.get(Calendar.DAY_OF_MONTH);
			showDialog(ID_DATEPICKER);
		}
	};

	private Button.OnClickListener timePickerButtonOnClickListener
	= new Button.OnClickListener(){
		@Override
		public void onClick(View v) {
			final Calendar c = Calendar.getInstance();
			myHour = c.get(Calendar.HOUR_OF_DAY);
			myMinute = c.get(Calendar.MINUTE);
			showDialog(ID_TIMEPICKER);
		}
	};


	private Button.OnClickListener hereButtonOnClickListener
	= new Button.OnClickListener(){
		@Override
		public void onClick(View v) {
			displayCurrentLocation();
		}
	};

	private Button.OnClickListener mapButtonOnClickListener
	= new Button.OnClickListener(){
		@Override
		public void onClick(View v) {
			Intent i = new Intent(getBaseContext(), LocationChooserMap.class);
			/*option: the initial locaiton*/
			i.putExtra("lat", currLat);
			i.putExtra("lon", currLon);

			startActivityForResult(i, PICK_LOCATION_REQUEST);
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode,
			Intent data) {
		if (requestCode == PICK_LOCATION_REQUEST) {
			if (resultCode == RESULT_OK) {
				currLat = data.getIntExtra("lat", 0);
				currLon = data.getIntExtra("lon", 0);
				currAddr = data.getStringExtra("addr");

				EditText locationInput = (EditText) findViewById(R.id.blipcreate_locationText);
				locationInput.setText(currAddr);
			}
		}
	}


	private Button.OnClickListener favsButtonOnClickListener
	= new Button.OnClickListener(){
		@Override
		public void onClick(View v) {

		}
	};


	private Button.OnClickListener confirmButtonOnClickListener
	= new Button.OnClickListener(){
		@Override
		public void onClick(View v) {
			sendBlip();

		}
	};

	private Button.OnClickListener cancelButtonOnClickListener
	= new Button.OnClickListener(){
		@Override
		public void onClick(View v) {
			finish();
		}
	};


	private Blip collectFormData() {
		Blip b = new Blip();

		//Tags - assumes comma separated values
		EditText tagsInput = (EditText) findViewById(R.id.blipcreate_tagsText);
		String tags= tagsInput.getText().toString();
		b.addTags(tags);

		//Description
		EditText descriptionInput = (EditText) findViewById(R.id.blipcreate_descriptionText);  
		String description = descriptionInput.getText().toString();
		b.setDescription(description);

		//Location
		GeoPoint p = new GeoPoint(currLat, currLon);
		b.setLocation(p);

		//Time
		b.setEventTime(currDate);
		return b;

	}

	private void sendBlip() {
		Button confirmButton = (Button)findViewById(R.id.blipcreate_confirmButton);
		confirmButton.setEnabled(false);
		Blip blip = collectFormData();
		blipManager.sendBlip(blip);
		Toast.makeText(getBaseContext(), "Blip Sent!", Toast.LENGTH_SHORT).show();
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		switch(id){
		case ID_DATEPICKER:
			return new DatePickerDialog(this,
					myDateSetListener,
					myYear, myMonth, myDay);
		case ID_TIMEPICKER:
			return new TimePickerDialog(this,
					myTimeSetListener,
					myHour, myMinute, false);
		default:
			return null;

		}
	}

	private DatePickerDialog.OnDateSetListener myDateSetListener
	= new DatePickerDialog.OnDateSetListener(){

		@Override
		public void onDateSet(DatePicker view, int year, 
				int monthOfYear, int dayOfMonth) {
			// TODO Auto-generated method stub
			Log.d("RADAR", "YEAR: " + year);
			currDate.setYear(year - 1900);
			currDate.setMonth(monthOfYear);
			currDate.setDate(dayOfMonth);
			displayTime();
		}
	};

	private TimePickerDialog.OnTimeSetListener myTimeSetListener
	= new TimePickerDialog.OnTimeSetListener(){

		@Override
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			// TODO Auto-generated method stub
			currDate.setHours(hourOfDay);
			currDate.setMinutes(minute);
			displayTime();
		}
	};


	private void displayTime() {
		EditText locationInput = (EditText) findViewById(R.id.blipcreate_timeText);
		locationInput.setText(Util.timeFormat(currDate));
	}
	
	private void displayCurrentLocation() {
		LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
		Location l = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		double lat = l.getLatitude();
		double lon = l.getLongitude();
		currLat = (int) (lat * 1E6); 
		currLon = (int) (lon * 1E6);
		
		try {
			List<Address> addresses = geoCoder.getFromLocation(lat,lon, 1);
			
			String add = "";
			if (addresses.size() > 0) 
				for (int i=0; i<addresses.get(0).getMaxAddressLineIndex(); i++)
					add += addresses.get(0).getAddressLine(i) + "\n";
			
			currAddr = add.trim();
			EditText locationInput = (EditText) findViewById(R.id.blipcreate_locationText);
			locationInput.setText(currAddr);
		} catch (IOException e) {e.printStackTrace();
			Toast.makeText(getBaseContext(), "Cannot retrieve address for current location", Toast.LENGTH_SHORT).show();
		}
	}
}


